layui.use(['table', 'admin', 'ax'], function () {
    var $ = layui.$;
    var table = layui.table;
    var $ax = layui.ax;
    var admin = layui.admin;

    /**
     * Inbound Order Management - 入库订单管理
     */
    var OrderPut = {
        tableId: "orderPutTable"
    };

    /**
     * Inbound Order Detail Management - 入库订单明细管理
     */
    var OrderPutDetailed = {
        tableId: "orderPutDetailedTable"
    };

    /**
     * Initialize table columns
     */
    OrderPut.initColumn = function () {
        return [[
            {type: 'checkbox'},
            {field: 'id', hide: true, title: 'ID'},
            {field: 'billstate', title: 'Status',templet: '#billstateTpl', event: 'billstateSign'},
            {field: 'putCustomerName', title: 'Customer'},
            {field: 'warehouseName', title: 'Warehouse'},
            {field: 'putNumber', title: 'System Order No', style:'color: #2b85e4;font-weight: 600;'},
            {field: 'putCustomerNumber',width:150, title: 'Customer Order No', style:'color: #2b85e4;font-weight: 600;'},
            {field: 'estimatetime', title: 'Estimated Inbound Time', hide: true},
            {field: 'putType', title: 'Inbound Type'},
            {field: 'putMode', title: 'Inbound Method'},
            {field: 'carnumber', title: 'Plate Number', hide: true},
            {field: 'shipmentnumber', title: 'Customer Delivery No', hide: true},
            {field: 'createTime', title: 'Creation Time'},
            {field: 'submissionTime', title: 'Submission Time'},
            {field: 'createName', title: 'Created By'},
            {field: 'submissionName', title: 'Submitted By'},
            {field: 'notes', title: 'Remarks'},
            {fixed: 'right',width: 90,align: 'center', toolbar: '#tableBar', title: 'Operation'}
        ]];
    };

    /**
     * Click search button
     */
    OrderPut.search = function () {
        var queryData = {};
        queryData['condition'] = $("#condition").val();
        queryData['putCustomerId'] = $("#putCustomerId").val();
        queryData['warehouseId'] = $("#warehouseId").val();
        table.reload(OrderPut.tableId, {
            where: queryData, page: {curr: 1},
             done:function () {
            }
        });
    };

	 // Import Excel
	 $('#btnExpimport').click(function () {
        layer.open({
            type: 2,
            title: 'Import Inbound Order',
            area: ['1000px', '600px'],
            anim: 5,
            content: Feng.ctxPath + '/orderPut/toimportExcel',
            end: function () {
                table.reload(OrderPut.tableId);
            }
        });
	 });

    $('#btnExpimportDD').click(function () {
        layer.open({
            type: 2,
            title: 'Import Inbound Order',
            area: ['1000px', '600px'],
            anim: 5,
            content: Feng.ctxPath + '/orderPut/toimportExcelDD',
            end: function () {
                table.reload(OrderPut.tableId);
            }
        });
    });

    /**
     * Open add dialog
     */
    OrderPut.openAddDlg = function () {
        window.location.href = Feng.ctxPath + '/orderPut/add';
    };

    /**
     * Export Excel button
     */
    OrderPut.exportExcel = function () {
        var checkRows = table.checkStatus(OrderPut.tableId);
        if (checkRows.data.length === 0) {
            Feng.error("Please select data to export");
        } else {
            table.exportFile(tableResult.config.id, checkRows.data, 'xls');
        }
    };

    /**
     * 点击编辑
     *
     * @param data 点击按钮时候的行数据
     */
    OrderPut.openEditDlg = function (data) {
        window.location.href = Feng.ctxPath + '/orderPut/edit?id=' + data.id;
    };

    // Render table
    var tableResult = table.render({
        elem: '#' + OrderPut.tableId,
        url: Feng.ctxPath + '/orderPut/list',
        page: true,
        limit: 40,
        height: 410,
        cellMinWidth: 100,
        toolbar: '#toolbarDemo', //开启头部工具栏，并为其绑定左侧模板
        cols: OrderPut.initColumn()
    });

     // Batch Submit
     $('#btnSubmission').click(function () {
    	var checkStatus = table.checkStatus('orderPutTable');
        data = checkStatus.data;
        if (data.length>0) {
            var ids = [];
            for (var i = 0; i < data.length; i++) {
            	ids.push(data[i].id);
			}
			
            layer.confirm('Confirm selected orders for submission?', function(index){
            	layer.close(index);
            	var msg;
                $.ajax({
                	url:Feng.ctxPath + "/orderPut/submission?ids="+ids,
                	cache: false,
                	dataType:"json",
                	beforeSend:function(){
                		msg = layer.msg('Submitting... Please wait patiently', {
                			  icon: 16,
                			  shade: [0.2,'#000'], //0.1透明度的白色背景
                			  time: false
                		});
                	},
                	success:function(data){
                    	layer.close(msg); 
                		if (data.success) {
                        	Feng.success("Submission successful!");
                			table.reload(OrderPut.tableId);
						} else {
							if (data.message !=null &&data.message!='') {
			    				var msg2 =  layer.open({
				  					  title: 'Notification' ,
				  					  content: data.message,
				  					  btn: ['Confirm'],
				  					  yes: function (){
				  						  	layer.close(msg2);
                							table.reload(OrderPut.tableId);
				  					  }
			    				});     
							} else {
	  		                    Feng.error("Submission failed!");
                				table.reload(OrderPut.tableId);
							}
						}
                	},
                	error:function(data){
                    	layer.close(msg); 
                        Feng.error("Submission failed! " + data.responseJSON.message)
                		table.reload(OrderPut.tableId);
                	}
                })
            }); 
		} else {
			layer.alert('Please select at least one record');
		}
     });

     // Batch Cancel
     $('#btnTovoid').click(function () {
    	var checkStatus = table.checkStatus('orderPutTable');
        data = checkStatus.data;
        if (data.length>0) {
            var ids = [];
            for (var i = 0; i < data.length; i++) {
            	ids.push(data[i].id);
			}
            var operation = function () {
                var ajax = new $ax(Feng.ctxPath + "/orderPut/tovoid?ids="+ids, function (data) {
                    Feng.success("Cancellation successful!");
                	table.reload(OrderPut.tableId);
                }, function (data) {
                    Feng.error("Cancellation failed! " + data.responseJSON.message + "!");
                });
                ajax.start();
            };
            Feng.confirm("Confirm cancellation of selected orders?", operation);
		} else {
			layer.alert('Please select at least one record');
		}
     });

    // Pull JST Purchase Inbound Orders
    $('#pulljstputorder').click(function () {
        submit = 2
        layer.open({
            type: 2,
            title: 'Pull JST Purchase Inbound Orders',
            area: ['850px', '600px'],
            anim: 5,
            content: Feng.ctxPath + '/toolOrderPut/topulljstputorderNew',
            end: function () {
                if(submit == 1){
                    table.reload(OrderPut.tableId);
                }
            }
        });
    });
    // Search button click event
    $('#btnSearch').click(function () {
        OrderPut.search();
    });

    // Add button click event - 添加按钮点击事件
    $('#btnAdd').click(function () {
        OrderPut.openAddDlg();
    });

    // Export Excel - 导出excel
    $('#btnExp').click(function () {
        OrderPut.exportExcel();
    });

    // Toolbar click event - 工具条点击事件
    table.on('tool(' + OrderPut.tableId + ')', function (obj) {
        var data = obj.data;
        var layEvent = obj.event;

        if (layEvent === 'edit') {
            OrderPut.openEditDlg(data);
        } else if (obj.event === 'billstateSign'&&data.billstate=='Rejected') {
			var index = layer.open({
				title: 'Audit Details:'},{
			    type: 1,
			    title: false, //不显示标题栏
			    closeBtn: false,
			    shade: 0.3,
		        area: '300px;',
	        	content: "<div style='padding: 50px; word-wrap: break-word;word-break: break-all;overflow: hidden; background-color: #393D49; color: #fff;line-height: 22px;  font-weight: 300;'>Auditor："+data.examineName+"<br><br>Audit Time："+data.examineTime+"<br><br>Comments：<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"+data.content+"</div>"},{
	            btn: ['Confirm'] ,
	            yes: function(){
	                layer.close(index);
	            }
	    	});
        } 
    });
    
    /**
     * Initialize table columns
     */
    OrderPutDetailed.initColumn = function () {
        return [[
            {field: 'id', hide: true, title: 'ID'},
            {field: 'detailedFactory', title: 'Factory No', hide: true},
            {field: 'recommend', title: 'Inbound Batch'},
            {field: 'detailedGoodsname', title: 'Product Name', style:'background-color: #dbf1e1;font-weight: 600;',width: 270},
            {field: 'goodsNumber', title: 'Product Code', style:'background-color: #dbf1e1;font-weight: 600;'},
            {field: 'goodsNo', title: 'SKU No', style:'background-color: #dbf1e1;font-weight: 600;', totalRowText: 'Total:'},
            {field: 'detailedPutnum', title: 'Expected Qty', totalRow: true, style:'background-color: #dbf1e1;font-weight: 600;'},
            {field: 'detailedDateofmanufacture', title: 'Manufacturing Date', style:'background-color: #dbf1e1;font-weight: 600;',width: 140},
            {field: 'detailedBatchnumber', title: 'Batch No', style:'background-color: #dbf1e1;font-weight: 600;',width: 140},
            {field: 'detailedPutweight', title: 'Expected Weight', totalRow: true},
            {field: 'detailedPutvolume', title: 'Expected Volume', totalRow: true},
            {field: 'detailedUnitprice', title: 'Unit Price'},
            {field: 'detailedMoney', title: 'Amount', totalRow: true},
            {field: 'detailedLargeclass', title: 'Category', hide: true},
            {field: 'detailedGoodstype', title: 'Type', hide: true},
            {field: 'goodsUnit', title: 'Unit'},
            {field: 'detailedPacking', title: 'Packaging'},
            {field: 'goodsSpecs', title: 'Specifications'},
            {fixed: 'right',width: 140,align: 'center', toolbar: '#tableBarDetailed', title: 'Operations'}
        ]];
    };

    // Click row event - 单击行事件
    table.on('row(' + OrderPut.tableId + ')', function (obj) {
        var data = obj.data;
		$('div[lay-id="' + OrderPut.tableId + '"]').find(".layui-table-body tr ").attr({ "style": "background:#FFFFFF" });//Other rows return to original state - 其他tr恢复原样
		$('div[lay-id="' + OrderPut.tableId + '"]').find(obj.tr.selector).attr({ "style": "background:#e6e6e6" });//Change current row color - 改变当前tr颜色
        orderPut(data);
    });
    
    function orderPut(data){
    	var putNumber;
    	if (data!=null) {
    		$("#putDetailedNumber").val(data.putNumber);
    		putNumber = data.putNumber;
		} else {
			putNumber = 'nodata';
		}
        // Render product details table
        var tableResult = table.render({
            elem: '#' + OrderPutDetailed.tableId,
            url: Feng.ctxPath + '/orderPutDetailed/list?putDetailedNumber=' + putNumber,
            page: true,
            limit: 30,
            height: 400,
            toolbar: '#toolbarfromDetailed',
            cellMinWidth: 100,
            totalRow: true ,//Enable total row
            cols: OrderPutDetailed.initColumn()
        });

        /**
         * Click search button
         */
    	OrderPutDetailed.search = function () {
            var queryData = {};
            queryData['condition'] = $("#condition2").val();
            table.reload(OrderPutDetailed.tableId, {
                where: queryData, page: {curr: 1},
                 done:function () {
                     // 搜索按钮点击事件
                     $('#btnSearchDetailed').click(function () {
                    	 OrderPutDetailed.search();
                     });
			        $('#btnAddDetailed').click(function () {
			        	OrderPutDetailed.addDetailed();
			        });
                }
            });
        };

    	OrderPutDetailed.addDetailed = function () {
            layer.open({
                type: 2,
                title: 'Detail Entry',
                area: ['1000px', '750px'],
                anim: 5,
                content: Feng.ctxPath + '/orderPutDetailed/add?putDetailedNumber=' + data.putNumber+"&putCustomerId="+data.putCustomerId,
                end: function () {
                	orderPut(data);
                }
            });
        };

        // Toolbar click event - 工具条点击事件
        table.on('tool(' + OrderPutDetailed.tableId + ')', function (obj) {
            var data2 = obj.data;
            var layEvent = obj.event;

            if (layEvent === 'editDetailed') {
                OrderPutDetailed.openEditDlg(data2);
            } else if (layEvent === 'deleteDetailed') {
                OrderPutDetailed.onDeleteItem(data2);
            }
        });

        // Edit button click event - 修改按钮点击事件
        OrderPutDetailed.openEditDlg = function (data2) {
            layer.open({
                type: 2,
                title: 'Detail Edit',
                area: ['1000px', '750px'],
                anim: 5,
                content: Feng.ctxPath + '/orderPutDetailed/edit?id='+data2.id+"&putDetailedNumber="+data.putNumber+"&putCustomerId="+data.putCustomerId,
                end: function () {
                	orderPut(data);
                }
            });
        };

        // Delete button click event - 删除按钮点击事件
        OrderPutDetailed.onDeleteItem = function (data2) {
            var operation = function () {
                var ajax = new $ax(Feng.ctxPath + "/orderPutDetailed/delete", function (data2) {
                    Feng.success("Deletion successful!");
                	orderPut(data);
                }, function (data) {
                    Feng.error("Deletion failed! " + data.responseJSON.message + "!");
                });
                ajax.set("id", data2.id);
                ajax.start();
            };
            Feng.confirm("Confirm deletion?", operation);
        };

        // Search button click event - 搜索按钮点击事件
        $('#btnSearchDetailed').click(function () {
        	OrderPutDetailed.search();
        });

        $('#btnAddDetailed').click(function () {
        	OrderPutDetailed.addDetailed();
        });
    }
    
});
